package com.fyy.im.server.handler;

import com.fyy.im.message.GCRequestMessage;
import com.fyy.im.message.GCResponseMessage;
import com.fyy.im.server.session.Group;
import com.fyy.im.server.session.GroupSession;
import com.fyy.im.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * @Author fyy
 * @Description
 * @Date 2021/5/12 15:12
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GCRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GCRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        //群管理器
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName,members);
        if(null == group){
            //发送成功消息
            ctx.writeAndFlush(new GCResponseMessage(true,"分组"+groupName+"创建成功！"));
            //发送入群消息
            List<Channel> channels = groupSession.getMembersChannel(groupName);
            for (Channel channel : channels) {
                channel.writeAndFlush(new GCResponseMessage(true,"您已被拉入"+groupName));
            }
        }else{
            ctx.writeAndFlush(new GCResponseMessage(false,"分组"+groupName+"已存在！"));
        }
    }

}
